package cz.cvut.kadledav.paa.knapsack.util;

import cz.cvut.kadledav.paa.knapsack.bo.Instance;
import cz.cvut.kadledav.paa.knapsack.bo.InstanceSolution;
import cz.cvut.kadledav.paa.knapsack.bo.Item;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: David Kadlecek
 * Date: 7.10.13
 */
public class KnapsackFileReadUtil {

    public static List<Instance> readInstances(String path) throws IOException {
        List<Instance> list = new ArrayList<>();
        try(BufferedReader file = new BufferedReader(new FileReader(path))){
            String line = file.readLine();
            while (line != null) {
                Instance instance = new Instance();
                StringTokenizer tokenizer = new StringTokenizer(line);
                instance.setInstanceId(Integer.valueOf(tokenizer.nextToken()));
                int n = Integer.valueOf(tokenizer.nextToken());
                instance.setItems(new ArrayList<Item>(n));
                instance.setMaxWeight(Integer.valueOf(tokenizer.nextToken()));
                for (int i = 0; i < n; i++) {
                    int weight = Integer.valueOf(tokenizer.nextToken());
                    int price = Integer.valueOf(tokenizer.nextToken());
                    instance.getItems().add(new Item(i, weight, price));
                }
                list.add(instance);
                line = file.readLine();
            }
            return list;
        }
    }

    public static Map<Integer, InstanceSolution> readSolutions(String path) throws IOException {
        Map<Integer, InstanceSolution> map = new HashMap<>();
        try(BufferedReader file = new BufferedReader(new FileReader(path))){
            String line = file.readLine();
            while (line != null) {
                InstanceSolution solution = new InstanceSolution();
                StringTokenizer tokenizer = new StringTokenizer(line);
                solution.setInstanceId(Integer.valueOf(tokenizer.nextToken()));
                int n = Integer.valueOf(tokenizer.nextToken());
                solution.setItemIds(new HashSet<Integer>(n));
                solution.setPrice(Integer.valueOf(tokenizer.nextToken()));
                for (int i = 0; i < n; i++) {
                    if("1".equalsIgnoreCase(tokenizer.nextToken())){
                        solution.getItemIds().add(i);
                    }
                }
                map.put(solution.getInstanceId(),solution);
                line = file.readLine();
            }
        }
        return map;
    }
}
